/**
 * 事件监听器
 */
var EventManager = cc.Class.extend({
    /**
     * 事件列表
     * @type {Object}
     * @private
     */
    _events: {},
    /**
     * 构造
     */
    ctor: function () {
        this._events = {};
    },
    /**
     * 添加监听
     * @param {String} key
     * @param {Function} callback
     * @param {View} target
     * @public
     */
    addListener: function (key, callback, target) {
        if (!key) {
            cc.error('key不能为空!');
            return;
        }
        if (!callback) {
            cc.error('callback不能为空!');
            return;
        }
        if (this._findListener(key, target)) {
            cc.error('重复添加监听!  key  = ' + key);
            this.removeListener(key, target);
        }
        var handler = {
            target: target,
            callback: callback
        };
        if (!this._events[key]) {
            this._events[key] = [];
        }
        this._events[key].push(handler);
    },
    /**
     * 发送消息
     * @param {String} key
     * @param {*} [data]
     * @param {Number} [errorCode]
     */
    dispatchEvent: function (key, data, errorCode) {
        console.log('dispatchEvent: ' + key);
        if (!key) {
            cc.error('key不能为空!');
            return;
        }
        if (!this._events.hasOwnProperty(key)) {
            cc.error('发送的消息没有接收者 : key = ' + key);
            return;
        }
        var handlers = this._events[key];
        _.forIn(handlers, function (handler) {
            handler.callback(data, errorCode);
        });
    },
    /**
     * 删除监听
     * @param {String} key
     * @param {View} target
     */
    removeListener: function (key, target) {
        if (!this._events.hasOwnProperty(key)) {
            return null;
        }
        var handlers = this._events[key];
        _.remove(handlers, function (handler) {
            return handler.target == target;
        });
    },
    /**
     * 删除监听
     * @param {View} target
     */
    removeListeners: function (target) {
        _.forIn(this._events, function (handlers) {
            if (!handlers) {
                handlers = [];
            }
            _.remove(handlers, function (handler) {
                return handler.target == target;
            });
        });
    },
    /**
     * 判断是否有重复监听
     * @param {String} key
     * @param {View} target
     * @return {*}
     * @private
     */
    _findListener: function (key, target) {
        if (!this._events.hasOwnProperty(key)) {
            return null;
        }
        var handlers = this._events[key];
        return _.find(handlers, function (handler) {
            return handler.target == target;
        });
    }
});